﻿package social.VKontakte
{
	import com.junkbyte.console.Cc;
	
	import social.Constants;
	
	import vk.api.serialization.json.JSON;
	
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.events.Event;
	import flash.events.EventDispatcher;		
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.system.Security;
	
	public class VKFlashVars extends EventDispatcher
	{			
		public static const SERVER_KEY_LOADED:String = 'SERVER_KEY_LOADED';
		
		public var ViewerID:String;
		public var AppID:String;
		public var SessionID:String;
		public var Secret:String;
		public var AccessToken:String;
		public var AppKey:String;
		public var APIPath:String;
		public var ServerKey:String;		
			
		private var FTestMode:Boolean;
		private var FKeyLoader:URLLoader;
		
		public function VKFlashVars(ATarget:Object, ACheckTestMode:Boolean):void
		{
			ServerKey = new String('');
			FKeyLoader = new URLLoader();
			if(ATarget)
			{
				ViewerID = ATarget["viewer_id"];				
				AppID = ATarget["api_id"];
				SessionID = ATarget["sid"];
				Secret = ATarget["secret"];
				AccessToken = ATarget["access_token"];
				APIPath = Constants.VK_API;
				
				FTestMode = ViewerID == null;
				
				if(ACheckTestMode)
				{
					CheckTestMode(ATarget);
				}
			}
			
			AppKey = Constants.VK_APP_KEY;
		}
		
		public function get TestMode():Boolean
		{
			return FTestMode;
		}
		
		public function CheckTestMode(ATarget:Object):void
		{
			if(TestMode)
			{				
				ViewerID = Constants.VK_TEST_VIEWER;
				AppID = Constants.VK_APP_ID;
				SessionID = Constants.VK_TEST_SID;
				Secret = Constants.VK_TEST_SECRET;
				APIPath = Constants.VK_API;
				
				ATarget["viewer_id"] = ViewerID;
				ATarget["api_id"] = AppID;
				ATarget["sid"] = SessionID;
				ATarget["secret"] = Secret;
			}
		}
		
		public function LoadServerKey(AURL:String):void
		{			
			FKeyLoader.addEventListener(Event.COMPLETE, OnKeyLoaded);
			FKeyLoader.addEventListener(IOErrorEvent.IO_ERROR, OnIOError);
			FKeyLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, OnSecurityError);
			FKeyLoader.load(new URLRequest(AURL));
		}
		
		private function OnIOError(e:IOErrorEvent):void
		{
			Cc.errorch('VKProvider', e.text);
		}
		
		private function OnSecurityError(e:SecurityErrorEvent):void
		{
			Cc.errorch('VKProvider', e.text);
		}
		
		private function OnKeyLoaded(e:Event):void
		{			
			var vResponse:Object = JSON.decode(FKeyLoader.data);
			ServerKey = vResponse.access_token;
			
			Cc.logch('VKProvider', 'Server key: ' + String(FKeyLoader.data));
			dispatchEvent(new Event(SERVER_KEY_LOADED));
		}
	}	
}
